package com.jianjun.framework.web.handler;

import com.jfinal.handler.Handler;
import com.jfinal.kit.StrKit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Pattern;

/**
 *
 * @author source
 * {@code @date} 2025/1/17 15:07
 */
public class XssHandler extends Handler {

    // 排除的url，使用的target.startsWith匹配的
    private final String excludePattern;

    /**
     * 忽略列表，使用正则排除url
     */
    public XssHandler(String excludePattern) {
        this.excludePattern = excludePattern;
    }

    @Override
    public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
        Pattern pattern = Pattern.compile(excludePattern);
        //带.表示非action请求，忽略（其实不太严谨，如果是伪静态，比如.html会被错误地排除）；匹配excludePattern的，忽略
        if (!target.contains(".") && !(!StrKit.isBlank(excludePattern) && pattern.matcher(target).find())) {
            request = new XssHttpServletRequestWrapper(request);
        }
        next.handle(target, request, response, isHandled);
    }

}
